//
//  TitleCollectionVC.m
//  TodayFirstNews
//
//  Created by 向祖华 on 16/3/3.
//  Copyright © 2016年 向祖华. All rights reserved.
//

#import "TitleCollectionVC.h"
#import "TitleCollectionViewCell.h"
#import "TitleCollectionModel.h"
#import "TitleCollectionReusableView.h"
#import "MainPageViewController.h"

static NSString* const classifyUrl = @"http://ic.snssdk.com/2/all/category/8/?user_city=%E7%A6%8F%E5%B7%9E&server_city=%E7%A6%8F%E5%B7%9E&iid=2321199393&device_id=2746583375&ac=wifi&channel=wo&aid=13&app_name=news_article&version_code=362&device_platform=android&device_type=HTC%20606w&os_api=16&os_version=4.1.2&uuid=356380052443211&openudid=55185e2a7b29b00";
static BOOL isEditing = NO;

@interface TitleCollectionVC ()<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property(nonatomic,strong)NSMutableArray * unSelectedTitleArr;//存放所有标题
@property(nonatomic,strong)NSMutableArray * allImageUrlArr;//存放所有图片的链接
@property(nonatomic,strong)NSMutableArray * allArrData;//网络请求数据以模型存储的数组
@property(nonatomic,strong)NSMutableArray * arr;//二维数组，存放已选择和未选择的标题数组

@end

@implementation TitleCollectionVC

- (void)viewDidLoad {
    [super viewDidLoad];
    //
    self.view.backgroundColor = [UIColor whiteColor];
    //设置代理
    self.collectionV.delegate = self;
    self.collectionV.dataSource = self;
    //collectionView的属性设置
    self.collectionV.backgroundColor = [UIColor whiteColor];
    self.collectionV.scrollEnabled = YES;
    //注册header
    [self.collectionV registerNib:[UINib nibWithNibName:@"TitleCollectionReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"collection_header"];
    //初始化原始标题数组
//    self.initialArr = [NSMutableArray arrayWithObjects:@"推荐",@"国际",@"财经",@"体育",@"教育",@"热点", nil];
    //初始数组存如大数组，下标为0
    [self.arr addObject:self.initialArr];
    //处理数据
    [self getData];
    
    
}
#pragma mark - 数据处理
-(void)getData{
    NSURL * url = [NSURL URLWithString:classifyUrl];
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
    NSURLSession * session = [NSURLSession sharedSession];
    NSURLSessionTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data) {
            NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            for (NSDictionary*dic1 in dic[@"data"]) {
                TitleCollectionModel * model = [[TitleCollectionModel alloc] init];
                
                [model setValuesForKeysWithDictionary:dic1];
                
                [self.allImageUrlArr addObject:model.image];
                [self.unSelectedTitleArr addObject:model.name];
                [self.allArrData addObject:model];
            }
            [self performSelectorOnMainThread:@selector(mainThread) withObject:nil waitUntilDone:YES];
        }
        //将所从网上取到的所有标题数组与初始标题数组进行去重融合，并存到arr
        for (NSString * titleStr in self.initialArr) {
            if ([self.unSelectedTitleArr containsObject:titleStr]) {
                [self.unSelectedTitleArr removeObject:titleStr];
            }
        }
        //未选择数组存入大数组，下标为1
        [self.arr addObject:self.unSelectedTitleArr];
    }];
    [task resume];
}

-(void)mainThread{
    [self.collectionV reloadData];
}
#pragma mark - collectionView的代理方法
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return [self.arr[section] count];
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    NSLog(@"返回细胞个数为%ld",self.arr.count);
    return self.arr.count;
}
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    TitleCollectionViewCell*cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TitleCollectionViewCell" forIndexPath:indexPath];
    //设置cell上的button的属性
    cell.deletButton.layer.cornerRadius = 8;
    cell.deletButton.layer.borderWidth = 0.5;
    cell.deletButton.layer.borderColor = [UIColor redColor].CGColor;
    
        //判断是否为可编辑状态，不可编辑，隐藏删除按钮，可编辑，第一组显示删除按钮
    if (isEditing ==YES && (indexPath.section == 0)) {
        if (indexPath.row == 0) {
            [cell.deletButton setHidden:YES];
        }
        else{
        [cell.deletButton setHidden:NO];
        }
        
    }else if(isEditing == NO||indexPath.section == 1){
        [cell.deletButton setHidden:YES];
    }
    else{
        [cell.deletButton setHidden:YES];
    }
    cell.lable.text = self.arr[indexPath.section][indexPath.row];
    if (indexPath.row == [self.currentIndex integerValue]&&indexPath.section ==0) {
        cell.lable.textColor = [UIColor redColor];
    }
    return cell;
}
//header和foot
-(UICollectionReusableView*)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
   //重用
    TitleCollectionReusableView * headerV = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"collection_header" forIndexPath:indexPath];

    //设置lable和button的相关属性
    headerV.editButton.layer.borderColor = [UIColor redColor].CGColor;
    headerV.editButton.layer.borderWidth = 0.5;
    headerV.editButton.layer.cornerRadius = 12;
    //处理编辑按钮的文字跟随状态变化
    if (isEditing == NO) {
        [headerV.editButton setTitle:@"编 辑" forState:(UIControlStateNormal)];
    } else {
        [headerV.editButton setTitle:@"完 成" forState:(UIControlStateNormal)];
    }
    //处理每组的头视图标题
    if (indexPath.section == 0) {
        headerV.describeLabel.text = @"我的频道";
        headerV.editButton.hidden = NO;
        //添加点击事件
        [headerV.editButton addTarget:self action:@selector(editButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    }
    if (indexPath.section == 1) {
        headerV.describeLabel.text = @"频道推荐";
        headerV.editButton.hidden = YES;
        
    }
    return headerV;
}

//细胞点击事件
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    //点击第二组的细胞，则删除，并添加到第一组
    if (indexPath.section == 1) {
        [self.arr[0] addObject:self.arr[1][indexPath.row]];
        [self.arr[1] removeObject:self.arr[1][indexPath.row]];
    }else{//点击第一组的细胞
        //如果为编辑状态则删除，并添加到第二组
        if (isEditing == YES&&indexPath.row != 0) {
            [self.arr[1] addObject:self.arr[0][indexPath.row]];
            [self.arr[0] removeObject:self.arr[0][indexPath.row]];
            NSInteger currentIndexNumber = [self.currentIndex integerValue];
            if (indexPath.row <currentIndexNumber) {
                
                self.currentIndex = [NSNumber numberWithInteger:(currentIndexNumber-1)];
            }

        }else{//如果为非编辑状态则跳转到相应的界面
            if (self.delegate && [self.delegate respondsToSelector:@selector(sendTitleArr:index:)]) {
                [self.delegate sendTitleArr:self.arr[0]index:indexPath.row];
                
                [self dismissViewControllerAnimated:YES completion:^{
                    NSLog(@"title界面代理传值%@",self.arr[0]);
                }];
                
            }
        }
    }
    //重新加载collectionView的界面
    [self.collectionV reloadData];
}
//编辑按钮点击事件
-(void)editButtonAction:(UIButton *)button{
    if (isEditing == YES) {
        isEditing = NO;
        button.titleLabel.text = @"完 成";
    }else{
        isEditing = YES;
        button.titleLabel.text = @"编 辑";
    }
    [self.collectionV reloadData];
}

#pragma mark - 懒加载
-(NSMutableArray *)allImageUrlArr{
    if (!_allImageUrlArr) {
        _allImageUrlArr = [[NSMutableArray alloc] init];
    }
    return _allImageUrlArr;
}

-(NSMutableArray *)unSelectedTitleArr{
    if (!_unSelectedTitleArr) {
        _unSelectedTitleArr = [[NSMutableArray alloc]init];
    }
    return _unSelectedTitleArr;
}
-(NSMutableArray *)allArrData{
    if (!_allArrData) {
        _allArrData = [[NSMutableArray alloc] init];
    }
    return _allArrData;
}
-(NSMutableArray *)arr{
    if (!_arr) {
        _arr = [[NSMutableArray alloc] init];
    }
    return _arr;
}

//返回按钮

- (IBAction)backButtonAction:(UIButton *)sender {

    if (self.delegate && [self.delegate respondsToSelector:@selector(sendTitleArr:index:)]) {
        //取到之前界面显示的位置
        NSInteger displayIndex = [self.currentIndex integerValue];
        
        [self.delegate sendTitleArr:self.arr[0]index:displayIndex];
        
        [self dismissViewControllerAnimated:YES completion:nil];
        
    }
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
